<template>
  <div v-loading="loadingSubmit">
    <Header :isGoBack="false">
      <template v-slot:right>
        <div class="test-btn">
          <span>计时：{{ testTime | filterTime }}</span>
          <span class="btn-bg ml20">
            <el-button
              class="button button-bg-second"
              :disabled="$store.getters.isTeacher"
              @click="postPaper"
              >交卷</el-button
            >
          </span>
          <span class="btn-bg ml20">
            <el-button
              class="button button-border-second"
              @click="goStudyCenter"
            >
              返回学习中心
            </el-button>
          </span>
        </div>
      </template>
    </Header>
    <div class="exercise-read text-test-paper">
      <div class="exercise-read-container text-test-paper-container w1200">
        <div class="container-title">
          <div></div>
          <span class="remind-text">
            <span>
              <div class="grade-read">
                <span class="standard-right">已录音</span>
                <span class="general-right">当前选中</span>
                <span class="delete-error">待录音</span>
              </div>
            </span>
          </span>
        </div>
        <div class="text-book-item text-book-left container-text">
          <div class="text-book-container-header">
            <span class="title">
              闯关测试({{ type == 1 ? "单句跟读" : "全文背诵" }})-
              {{ title }}
            </span>
          </div>
          <div class="reading-article mr20 text-book-contain">
            <div class="text-book-contain-box">
              <div class="audio-record">
                <div class="remind-text">点击切换下一句</div>
                <AudioRecord
                  @start="handleStart"
                  @ended="handleEnd"
                  @clickStart="audioRecordStart()"
                  @clickEnd="
                    () => {
                      audioRecordEnd();
                    }
                  "
                  @beforeSatrt="beforeRecordSatrt"
                  :ref="`audioRecord`"
                  :type="2"
                ></AudioRecord>
              </div>
              <div class="text-paragraph-list scrollbar">
                <div class="scorll-box">
                  <div
                    class="text-book-paragraph"
                    v-for="(item, index) in sentenceList"
                    :key="item.id"
                    :id="`text-book-paragraph-${index}`"
                  >
                    <div class="name" v-if="item.name">{{ item.name }}:</div>
                    <div
                      class="paragraph click"
                      :class="[
                        playNum == index ? 'play-paragraph' : '',
                        item.result ? 'answered-paragraph' : '',
                      ]"
                      @click="changePlayNum(index)"
                    >
                      <div
                        class="content"
                        :class="type == 2 ? 'hidden-text' : ''"
                      >
                        <span>{{ item.content }}</span>
                      </div>
                      <div v-if="type == 2" class="translation mt10">
                        {{ item.translation }}
                      </div>
                    </div>
                  </div>
                </div>
              </div>
            </div>
          </div>
        </div>
      </div>
    </div>
  </div>
</template>
<script>
import Header from "@/components/Header";
import AudioRecord from "@/components/AudioRecord";
import {
  postTestParagraphRecord,
  getTestPaper,
  postTestScore,
} from "@/api/text";

export default {
  data() {
    return {
      language: 2,
      sentenceList: [],
      title: "Unit 1 A-Let's talk.",
      audioSrc:
        "imgs/audio/2021-02-01/e0060a91-d2e9-4b93-9161-be61590b89d0.mp3",
      playNum: 0,
      isPlayParagraph: false,
      type: 1,
      testTime: 0,
      hasRecording: false,
      loadingSubmit: false,
    };
  },
  methods: {
    goStudyCenter() {
      this.$confirm(`试卷还未提交，是否退出`, "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        closeOnClickModal: false,
        closeOnPressEscape: false,
      })
        .then(() => {
          this.$router.push({
            name: "textStudyCenter",
          });
        })
        .catch(() => {
          return false;
        });
    },
    acceptAudioPlay(data) {
      this.isPlayParagraph = data;
    },
    timerFun() {
      this.timer = setInterval(() => {
        this.testTime++;
      }, 1000);
    },
    getText() {
      let data = {
        book_id: this.checkedBookData.book_id,
        unit_id: this.unitId,
        category: this.type,
      };
      getTestPaper({}, data).then((res) => {
        if (res.code == 200 && res.data) {
          this.textData = res.data;
          this.sentenceList = res.data.list.map((item) => {
            return {
              id: item.sentence_id,
              content: item.content,
              translation: item.translation,
              name: item.name,
              result: null,
              score: 0,
              format: item.format,
            };
          });
          this.audioSrc = this.textData.audio_src;
          this.timerFun();
        }
      });
    },
    playParagraph(startTime, endTime) {
      if (!this.isPlayParagraph) {
        this.playParagraphAudio(startTime, endTime);
      } else {
        this.pauseParagraphAudio();
      }
    },
    playParagraphAudio(startTime, endTime) {
      if (
        startTime &&
        endTime &&
        this.$refs.textAudio.currentTime &&
        this.$refs.textAudio.currentTime >= startTime &&
        this.$refs.textAudio.currentTime <= endTime
      ) {
        this.$refs.textAudio.playAudio();
      } else {
        this.$refs.textAudio.playAudio(startTime, endTime);
      }
    },
    pauseParagraphAudio() {
      this.$refs.textAudio.pauseAudio();
    },

    handleStart() {
      console.log("开始");
      this.hasRecording = true;
    },
    handleEnd() {
      console.log("结束");
      this.hasRecording = false;
    },
    // 点击录音开始前的回调
    beforeRecordSatrt() {},
    // 点击开始录音的回调
    audioRecordStart() {
      console.log("点击开始");
      //
    },
    // 点击结束录音的回调
    // sentence_id=181&content=I'm Mike.
    // http://localhost:8101/sound/save?word_id=121&word_name=testcc&is_child=1&accent=1
    audioRecordEnd(nextIndex) {
      let sentenceData = this.sentenceList[this.playNum];
      let blob = this.$refs[`audioRecord`].getMp3Data();
      let file = new window.File([blob], sentenceData.id + ".mp3", {
        type: blob.type,
      });
      let formData = new FormData();
      formData.append("sound_file", file);
      formData.append("sentence_id", sentenceData.id);
      formData.append("content", sentenceData.content);
      formData.append("is_child", 0);
      formData.append("accent", 1);
      // type:1 读 type:2背诵
      postTestParagraphRecord({}, formData).then((res) => {
        if (res.code == 200 && res.data) {
          sentenceData.score = res.data.score;
          sentenceData.result = res.data.context;
          if (nextIndex) {
            this.playNum = nextIndex;
            return;
          }
          let index = this.sentenceList.findIndex((item) => {
            return !item.result;
          });
          if (index == -1) {
            this.postPaper();
          } else {
            this.playNum = index;
          }
        }
      });
    },
    postTestScore(textPaperRes) {
      let params = {
        score: textPaperRes.paperScore,
        bookId: this.checkedBookData.book_id,
        unitId: this.unitId,
        category: this.type,
        useTime: textPaperRes.useTime,
        testId: textPaperRes.testId,
      };
      postTestScore(params).then((res) => {
        if (res.code == 200) {
          textPaperRes.addInt = res.data;
          console.log(res.data,545);
          localStorage.setItem("textPaperRes", JSON.stringify(textPaperRes));
          this.$router.push({
            name: "textTestReport",
            query: this.$route.query,
          });
        }
      });
    },
    changePlayNum(index) {
      if (this.hasRecording) {
        this.$refs.audioRecord.stopRecorder();
        this.audioRecordEnd(index);
      } else {
        this.playNum = index;
      }
    },
    /**
     *  获取麦克风权限
     * */
    getPermission() {
      this.$Recorder.getPermission().then(
        () => {
          console.log("获取权限成功");
        },
        (error) => {
          console.log(`${error.name} : ${error.message}`);
          if (error.name == "NotAllowedError") {
            this.$message({
              type: "error",
              message: `没有使用麦克风的权限`,
            });
          } else if (
            error.name == "NotFoundError" &&
            error.message == "Requested device not found"
          ) {
            this.$message({
              type: "error",
              message: `没有找到麦克风`,
            });
          } else {
            this.$message({
              type: "error",
              message: `${error.name} : ${error.message}`,
            });
          }
        }
      );
    },
    postPaper() {
      this.$confirm(`是否检查完毕，确认交卷`, "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        closeOnClickModal: false,
        closeOnPressEscape: false,
      })
        .then(() => {
          this.submitPaper();
        })
        .catch(() => {
          return false;
        });
    },
    submitPaper() {
      let totalScore = this.sentenceList.reduce((total, item) => {
        return total + item.score;
      }, 0);
      let paperScore = parseInt(totalScore / this.sentenceList.length);
      let textPaperRes = {
        useTime: this.testTime,
        testId: this.textData.test_id,
        audio_src: this.textData.audio_src,
        paperScore,
        sentenceList: this.sentenceList,
      };
      this.postTestScore(textPaperRes);
    },
  },
  created() {
    this.checkedBookData = JSON.parse(localStorage.getItem("bookData"));
    this.unitId = Number(this.$route.query.unitId);
    this.title = localStorage.getItem("checkedUnit")
      ? JSON.parse(localStorage.getItem("checkedUnit")).title
      : "";
    this.type = this.$route.query.type;
    this.getText();
  },
  mounted() {
   // this.getPermission();
  },
  beforeDestroy() {
    clearInterval(this.timer);
  },
  components: {
    Header,
    AudioRecord,
    // AudioPlay,
  },
};
</script>